<template>
  <div class="sandbox-config-container">
    <a-card class="header-card">
      <a-row>
        <a-col :span="12">
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索沙箱环境"
            style="width: 300px"
            @search="onSearch"
          />
        </a-col>
        <a-col :span="12" class="text-right">
          <a-button type="primary" @click="showCreateModal">
            <PlusOutlined />
            新增沙箱
          </a-button>
        </a-col>
      </a-row>
    </a-card>

    <a-card class="content-card">
      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane key="1" tab="沙箱列表">
          <a-table
            :data-source="sandboxList"
            :columns="columns"
            :pagination="pagination"
            @change="handleTableChange"
            :loading="loading"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag :color="record.status === 1 ? 'success' : 'error'">
                  {{ record.status === 1 ? '启用' : '禁用' }}
                </a-tag>
              </template>
              <template v-else-if="column.dataIndex === 'action'">
                <a-space>
                  <a-button type="link" @click="editSandbox(record)">编辑</a-button>
                  <a-button type="link" @click="deleteSandbox(record)">删除</a-button>
                  <a-button type="link" @click="switchSandbox(record)">
                    {{ currentSandbox && currentSandbox.id === record.id ? '使用中' : '切换' }}
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" tab="沙箱详情">
          <div v-if="currentSandbox">
            <a-descriptions title="沙箱信息" :column="2">
              <a-descriptions-item label="沙箱名称">{{ currentSandbox.name }}</a-descriptions-item>
              <a-descriptions-item label="环境地址">{{ currentSandbox.url }}</a-descriptions-item>
              <a-descriptions-item label="状态">
                <a-tag :color="currentSandbox.status === 1 ? 'success' : 'error'">
                  {{ currentSandbox.status === 1 ? '启用' : '禁用' }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="创建时间">{{ currentSandbox.createTime }}</a-descriptions-item>
              <a-descriptions-item label="描述" :span="2">{{ currentSandbox.description }}</a-descriptions-item>
            </a-descriptions>

            <a-divider />

            <h3>环境变量配置</h3>
            <a-table
              :data-source="envVars"
              :columns="envColumns"
              :pagination="false"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'action'">
                  <a-space>
                    <a-button type="link" @click="editEnvVar(record)">编辑</a-button>
                    <a-button type="link" @click="deleteEnvVar(record)">删除</a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
            <div style="margin-top: 20px; text-align: right;">
              <a-button type="primary" @click="addEnvVar">添加环境变量</a-button>
            </div>
          </div>
          <a-empty v-else description="请先选择一个沙箱环境" />
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 新增/编辑沙箱 Modal -->
    <a-modal
      v-model:open="modalVisible"
      :title="editingSandbox ? '编辑沙箱' : '新增沙箱'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="沙箱名称" required>
          <a-input v-model:value="form.name" placeholder="请输入沙箱名称" />
        </a-form-item>
        <a-form-item label="环境地址" required>
          <a-input v-model:value="form.url" placeholder="请输入环境地址" />
        </a-form-item>
        <a-form-item label="状态">
          <a-switch
            v-model:checked="form.status"
            checked-children="启用"
            un-checked-children="禁用"
          />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model:value="form.description" placeholder="请输入沙箱描述" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 环境变量 Modal -->
    <a-modal
      v-model:open="envModalVisible"
      :title="editingEnvVar ? '编辑环境变量' : '新增环境变量'"
      @ok="handleEnvModalOk"
      @cancel="handleEnvModalCancel"
    >
      <a-form :model="envForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="变量名" required>
          <a-input v-model:value="envForm.key" placeholder="请输入变量名" />
        </a-form-item>
        <a-form-item label="变量值" required>
          <a-input v-model:value="envForm.value" placeholder="请输入变量值" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model:value="envForm.description" placeholder="请输入变量描述" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

export default {
  name: 'SandboxConfig',
  components: {
    PlusOutlined
  },
  data() {
    return {
      searchText: '',
      activeTab: '1',
      loading: false,
      modalVisible: false,
      envModalVisible: false,
      editingSandbox: null,
      editingEnvVar: null,
      currentSandbox: null,
      form: {
        name: '',
        url: '',
        status: true,
        description: ''
      },
      envForm: {
        key: '',
        value: '',
        description: ''
      },
      sandboxList: [
        {
          id: 1,
          name: '开发环境',
          url: 'https://dev.example.com',
          status: 1,
          description: '开发测试环境',
          createTime: '2023-09-01 10:00:00'
        },
        {
          id: 2,
          name: '测试环境',
          url: 'https://test.example.com',
          status: 1,
          description: '功能测试环境',
          createTime: '2023-09-01 10:05:00'
        },
        {
          id: 3,
          name: '预发布环境',
          url: 'https://pre.example.com',
          status: 0,
          description: '预发布验证环境',
          createTime: '2023-09-01 10:10:00'
        }
      ],
      envVars: [
        {
          id: 1,
          key: 'API_KEY',
          value: 'xxxxxx',
          description: '接口访问密钥'
        },
        {
          id: 2,
          key: 'DEBUG_MODE',
          value: 'true',
          description: '调试模式开关'
        }
      ],
      columns: [
        {
          title: '沙箱名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '环境地址',
          dataIndex: 'url',
          key: 'url'
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status'
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action'
        }
      ],
      envColumns: [
        {
          title: '变量名',
          dataIndex: 'key',
          key: 'key'
        },
        {
          title: '变量值',
          dataIndex: 'value',
          key: 'value'
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action'
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 3
      }
    };
  },
  methods: {
    onSearch() {
      message.success('搜索功能已触发');
    },
    showCreateModal() {
      this.editingSandbox = null;
      this.form = {
        name: '',
        url: '',
        status: true,
        description: ''
      };
      this.modalVisible = true;
    },
    editSandbox(record) {
      this.editingSandbox = record;
      this.form = { ...record };
      this.form.status = record.status === 1;
      this.modalVisible = true;
    },
    deleteSandbox(record) {
      const that = this;
      this.$confirm({
        title: '确认删除',
        content: `确定要删除沙箱 "${record.name}" 吗？`,
        onOk() {
          // 模拟删除操作
          message.success('删除成功');
          that.sandboxList = that.sandboxList.filter(item => item.id !== record.id);
          if (that.currentSandbox && that.currentSandbox.id === record.id) {
            that.currentSandbox = null;
          }
        }
      });
    },
    switchSandbox(record) {
      this.currentSandbox = record;
      message.success(`已切换到沙箱: ${record.name}`);
    },
    handleModalOk() {
      if (!this.form.name || !this.form.url) {
        message.warning('请填写必填项');
        return;
      }

      if (this.editingSandbox) {
        // 编辑操作
        const index = this.sandboxList.findIndex(item => item.id === this.editingSandbox.id);
        this.sandboxList[index] = {
          ...this.form,
          id: this.editingSandbox.id,
          status: this.form.status ? 1 : 0,
          createTime: this.editingSandbox.createTime
        };
        message.success('编辑成功');
      } else {
        // 新增操作
        this.sandboxList.push({
          ...this.form,
          id: this.sandboxList.length + 1,
          status: this.form.status ? 1 : 0,
          createTime: new Date().toLocaleString()
        });
        message.success('新增成功');
      }
      this.modalVisible = false;
    },
    handleModalCancel() {
      this.modalVisible = false;
    },
    handleTableChange(pagination) {
      this.pagination = { ...pagination };
    },
    addEnvVar() {
      this.editingEnvVar = null;
      this.envForm = {
        key: '',
        value: '',
        description: ''
      };
      this.envModalVisible = true;
    },
    editEnvVar(record) {
      this.editingEnvVar = record;
      this.envForm = { ...record };
      this.envModalVisible = true;
    },
    deleteEnvVar(record) {
      this.envVars = this.envVars.filter(item => item.id !== record.id);
      message.success('删除成功');
    },
    handleEnvModalOk() {
      if (!this.envForm.key || !this.envForm.value) {
        message.warning('请填写必填项');
        return;
      }

      if (this.editingEnvVar) {
        // 编辑操作
        const index = this.envVars.findIndex(item => item.id === this.editingEnvVar.id);
        this.envVars[index] = { ...this.envForm, id: this.editingEnvVar.id };
        message.success('编辑成功');
      } else {
        // 新增操作
        this.envVars.push({
          ...this.envForm,
          id: this.envVars.length + 1
        });
        message.success('新增成功');
      }
      this.envModalVisible = false;
    },
    handleEnvModalCancel() {
      this.envModalVisible = false;
    }
  }
};
</script>

<style scoped>
.sandbox-config-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.content-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.text-right {
  text-align: right;
}
</style>